package com.autoplaza;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class MiFacebook extends Activity {

	Button mBtnPostStatus;
	private Facebook facebook;
	private String messageToPost, descripcion;
	public static final String APP_ID = "490198794354254";
	private static final String[] PERMISSIONS = new String[] { "publish_stream" };
	private static final String TOKEN = "access_token";
	private static final String EXPIRES = "expires_in";
	
	public final static String FACEBOOK = "com.smartthinking.wanagow.FACEBOOK";
	public final static String PREFS_NAME = "PreferenciasFacebook";
	
	boolean exito;
	public Dialog progressDialog;
	private String miMensaje = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.facebook);

		Intent intent = getIntent();
		messageToPost = intent.getStringExtra(FACEBOOK);
		descripcion = intent.getStringExtra("dato");
		facebook = new Facebook(APP_ID);
		restoreCredentials(facebook);
		if (!facebook.isSessionValid()) {
			loginAndPostToWall();
		} else {
			postToWall(messageToPost);
		}
	}

	public boolean saveCredentials(Facebook facebook) {
		Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
		editor.putString(TOKEN, facebook.getAccessToken());
		editor.putLong(EXPIRES, facebook.getAccessExpires());
		return editor.commit();
	}

	public boolean restoreCredentials(Facebook facebook) {
		SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
		facebook.setAccessToken(settings.getString(TOKEN, null));
		facebook.setAccessExpires(settings.getLong(EXPIRES, 0));
		return facebook.isSessionValid();
	}

	public void loginAndPostToWall() {
		facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
	}

	private class AsyncActividades extends AsyncTask<String, Void, Integer> {
		protected void onPostExecute(Integer in) {
			progressDialog.dismiss();
			
			if(exito){
				showToast("Mensaje agregado a su muro de facebook!");
			}else{
				showToast("Fallo al postear!");
			}
			finish();
		}

		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(MiFacebook.this, "", "Cargando...");
		}

		protected Integer doInBackground(String... urls) {
			Bundle parameters = new Bundle();
//			parameters.putString("message", miMensaje);
//			parameters.putString("description", "topic share");
			parameters.putString("name", "Te recomiendo el siguiente anuncio de Autoplaza");
			parameters.putString("caption", "Compartido desde App de Android de Autoplaza");
			parameters.putString("link", miMensaje);
		    parameters.putString("description",""+descripcion);
			exito = true;
			try {
				facebook.request("me");
				String response = facebook.request("me/feed", parameters, "POST");
				Log.d("Tests", "got response: " + response);
				if (response == null || response.equals("") || response.equals("false")) {
					//showToast("Sin respuesta.");
			    	//Intent resultIntent = getIntent();
			    	//setResult(Activity.RESULT_CANCELED, resultIntent);
			    	//finish();
				} else {
					//showToast("Mensaje agregado a su muro de facebook!");
			    	/*Intent resultIntent = getIntent();
			    	setResult(Activity.RESULT_OK, resultIntent);*/
			    	//finish();
				}
			} catch (Exception e) {
				exito = false;
				//showToast("Fallo al postear!");
				e.printStackTrace();
			}
			
		    return null;
		}
	}

	
	
	public void postToWall(String message) {
		miMensaje = message;
		new AsyncActividades().execute("contenido");
	}

	class LoginDialogListener implements DialogListener {
		public void onComplete(Bundle values) {
			saveCredentials(facebook);
			if (messageToPost != null) {
				postToWall(messageToPost);
			}
		}

		public void onFacebookError(FacebookError error) {
			showToast("Autenticación con Facebook fallida!");
			Intent resultIntent = getIntent();
	    	setResult(Activity.RESULT_CANCELED, resultIntent);
			finish();
		}

		public void onError(DialogError error) {
			showToast("Autenticación con Facebook fallida!");
			Intent resultIntent = getIntent();
	    	setResult(Activity.RESULT_CANCELED, resultIntent);
			finish();
		}

		public void onCancel() {
			showToast("Autenticación con Facebook cancelada!");
			Intent resultIntent = getIntent();
	    	setResult(Activity.RESULT_CANCELED, resultIntent);
			finish();
		}
	}

	private void showToast(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}
}